<?php

namespace app\index\controller;

use think\facade\Hook;
use think\Db;
use PHPMailer\PHPMailer\PHPMailer;

class Mail
{

    public function send()
    {

        return "发送成功";

        //echo "邮件发送成功";

        $res = $this->send_email("1741108471@qq.com","测试标题", "测试内容");

        var_dump($res);die;

    }

    /**
     * 邮件发送
     * @param $to 接收人
     * @param string $subject 邮件标题
     * @param string $content 邮件内容(html模板渲染后的内容)
     * @throws Exception
     * @throws phpmailerException
     */
    public function send_email($to, $subject = '', $content = '')
    {
        $config = [
            'smtp_server' => 'smtp.qq.com',
            'smtp_port' => 465,
            'smtp_user' => '2652364582@qq.com',
            'smtp_pwd' => 'ynxahoihduuhecbj',
            'email_id' => '北桥苏'
        ];

        $emails = new PHPMailer();

        $emails->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
        $emails->isSMTP();

        //Enable SMTP debugging
        // 0 = off (for production use)
        // 1 = client messages
        // 2 = client and server messages
        $emails->SMTPDebug = 0;

        //调试输出格式
        //$emails->Debugoutput = 'html';
        //smtp服务器
        $emails->Host = $config['smtp_server'];

        //端口 - likely to be 25, 465 or 587
        $emails->Port = $config['smtp_port'];

        if ($emails->Port === 465) $emails->SMTPSecure = 'ssl';// 使用安全协议
        //Whether to use SMTP authentication
        $emails->SMTPAuth = true;
        //发送邮箱
        $emails->Username = $config['smtp_user'];
        //密码
        $emails->Password = $config['smtp_pwd'];
        //Set who the message is to be sent from
        $emails->setFrom($config['smtp_user'], $config['email_id']);

        //回复地址
        //$emails->addReplyTo('replyto@example.com', 'First Last');

        // 接收邮件方
        if (is_array($to)) {

            foreach ($to as $v) {
                $emails->addAddress($v);
            }

        } else {

            $emails->addAddress($to);
        }

        $emails->isHTML(true);// send as HTML

        //标题
        $emails->Subject = $subject;

        //HTML内容转换
        $emails->msgHTML($content);

        //Replace the plain text body with one created manually
        //$emails->AltBody = 'This is a plain-text message body';

        //添加附件
        //$emails->addAttachment('images/phpmailer_mini.png');
        //send the message, check for errors

        return $emails->send();
    }


}
